#include "NDMutex.h"



NDMutex::NDMutex()
{
	m_bInited	= false;
}

NDMutex::~NDMutex()
{
	if (m_bInited) {
#ifdef NDMUTEX_CRITICALSECTION
		DeleteCriticalSection(&m_mutex);
#else
		CloseHandle(m_mutex);
#endif
	}
}

int NDMutex::Init()
{
	if(m_bInited) {
		return ERR_NDMUTEX_ALREADYINIT;
	}
#ifdef NDMUTEX_CRITICALSECTION
	InitializeCriticalSection(&m_mutex);
#else
	m_mutex = CreateMutex(NULL, FALSE, NULL);
#endif
	m_bInited = true; 
	return 0;
}

int NDMutex::Lock()
{
	if(!m_bInited) {
		return ERR_NDMUTEX_NOTINIT;
	}
#ifdef NDMUTEX_CRITICALSECTION
	EnterCriticalSection(&m_mutex);
#else
	WaitForSingleObject(m_mutex,  INFINITE);
#endif
	return 0;
}

int NDMutex::Unlock()
{
	if(!m_bInited) {
		return ERR_NDMUTEX_NOTINIT;
	}
#ifdef NDMUTEX_CRITICALSECTION
	LeaveCriticalSection(&m_mutex);
#else
	ReleaseMutex(m_mutex);
#endif
	return 0;
}

